//client.cpp，客户端
#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>
#pragma comment(lib, "Ws2_32.lib")

int main()
{
    //初始化Winsock
    WSADATA wsadata;
    if (WSAStartup(MAKEWORD(2, 2), &wsadata) != 0)
    {
        std::cerr << "Winsock初始化失败。" << std::endl;
        return 1;
    }

    //创建客户端socket
    SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (clientSocket == INVALID_SOCKET)
    {
        std::cerr << "创建客户端socket失败。" << std::endl;
        WSACleanup();
        return 1;
    }

    //设置服务器地址和端口
    sockaddr_in serverAddr = {};
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = inet_addr("192.168.156.29"); //替换为服务器的IP地址
    serverAddr.sin_port = htons(55666);

    //连接到服务器
    if (connect(clientSocket, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR)
    {
        std::cerr << "连接到服务器失败。" << std::endl;
        closesocket(clientSocket);
        WSACleanup();
        return 1;
    }

    //准备发送的许可证
    std::string serialNumber = "1234567890"; //替换为有效许可证

    //发送许可证到服务器
    int bytesSent = send(clientSocket, serialNumber.c_str(), serialNumber.size(), 0);
    if (bytesSent == SOCKET_ERROR)
    {
        std::cerr << "发送序列号失败。" << std::endl;
        closesocket(clientSocket);
        WSACleanup();
        return 1;
    }

    //接收服务器的响应
    char buffer[1024] = { 0 };
    int bytesRead = recv(clientSocket, buffer, sizeof(buffer) - 1, 0);
    if (bytesRead <= 0)
    {
        std::cerr << "接收服务器响应失败。" << std::endl;
        closesocket(clientSocket);
        WSACleanup();
        return 1;
    }

    //输出服务器的响应
    std::cout << "服务器响应：" << buffer << std::endl;

    //关闭客户端socket并清理Winsock
    closesocket(clientSocket);
    WSACleanup();

    return 0;
}